package resource

import (
	"sync"
)

// Manager manages resource allocation
type Manager struct {
	resources    map[string]bool
	maxResources int
	mutex        sync.RWMutex
}

// NewManager creates a new resource manager
func NewManager(maxResources int) *Manager {
	return &Manager{
		resources:    make(map[string]bool),
		maxResources: maxResources,
	}
}

// AcquireResource attempts to acquire a resource
func (r *Manager) AcquireResource(id string) bool {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	if len(r.resources) >= r.maxResources {
		return false
	}

	r.resources[id] = true
	return true
}

// ReleaseResource releases a resource
func (r *Manager) ReleaseResource(id string) {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	delete(r.resources, id)
}

// GetResourceCount returns the number of acquired resources
func (r *Manager) GetResourceCount() int {
	r.mutex.RLock()
	defer r.mutex.RUnlock()
	return len(r.resources)
}

// HasResource checks if a resource is acquired
func (r *Manager) HasResource(id string) bool {
	r.mutex.RLock()
	defer r.mutex.RUnlock()
	_, ok := r.resources[id]
	return ok
}

// GetMaxResources returns the maximum number of resources
func (r *Manager) GetMaxResources() int {
	return r.maxResources
}

// SetMaxResources sets the maximum number of resources
func (r *Manager) SetMaxResources(max int) {
	r.mutex.Lock()
	defer r.mutex.Unlock()
	r.maxResources = max
}
